import {types, getEnv, applySnapshot, getSnapshot} from 'mobx-state-tree';
import {PageStore} from './Page';
import {reaction} from 'mobx';
export const MainStore = types
  .model('MainStore', {
    pages: types.optional(types.array(PageStore), [
      {
        id: '1',
        path: 'form',
        label: 'form',
        icon: 'fa fa-form',
        schema: {
          type: 'form',
          title: '表单',
          body: []
        }
      }
    ]),
    theme: 'cxd',
    preview: false,
    isMobile: false,
    schema: types.frozen()
  })
  .views(self => ({
    get fetcher() {
      return getEnv(self).fetcher;
    },
    get notify() {
      return getEnv(self).notify;
    },
    get alert() {
      return getEnv(self).alert;
    },
    get copy() {
      return getEnv(self).copy;
    }
  }))
  .actions(self => {
    function updatePageSchemaAt(index: number) {
      self.pages[index].updateSchema(self.schema);
    }

    function updateSchema(value: any) {
      self.schema = value;
    }

    function setPreview(value: boolean) {
      self.preview = value;
    }

    function setIsMobile(value: boolean) {
      self.isMobile = value;
    }
    function postSave(data:any) {
      console.log("保存");
      window.parent.postMessage(
        {
          msg: data,
          key: 'formTemplateData'
        },
        '*'
      );
    }

    return {
      updatePageSchemaAt,
      updateSchema,
      setPreview,
      setIsMobile,
      postSave,
      afterCreate() {
        // persist store
        if (typeof window !== 'undefined' && window.localStorage) {
          const storeData = window.localStorage.getItem('currentFormTemplate');
          if (storeData) applySnapshot(self, JSON.parse(storeData));
          reaction(
            () => getSnapshot(self),
            json => {
              window.localStorage.setItem('currentFormTemplate', JSON.stringify(json));
            }
          );
        }
      }
    };
  });

export type IMainStore = typeof MainStore.Type;
